var express = require('express');
var router = express.Router();
// 引入mongoose， 启动数据库
const mongoose = require('mongoose')
const UserModel = require('../../models/user')
const ArticleModel = require('../../models/article')
const jwt = require('jwt-simple')
const moment = require('moment')
// var log4js = require('log4js');
var fs = require("fs");
var bodyParser = require('body-parser');
mongoose.connect('mongodb://localhost:27017/blog')
mongoose.connection.on('connected', function () {
  console.log('mongodb connected')
})
mongoose.connection.on('error', function () {
  console.log('mongodb error')
})
mongoose.connection.on('disconnected', function () {
  console.log('mongodb disconnected')
})

/* v1 api. */
const secretKey = '77lovePanda'

// 中间件尝试， 截取jwt中的用户信息
router.use('/', function(req, res, next) {
  const { token } = req.headers
  if (token) {
    let userInfo = {}
    try {
      userInfo = jwt.decode(token, secretKey)
    } catch (err) {
      console.log(err);
    }
    req._userInfo = {...userInfo}
  }
  next()
})

// 登录
router.post('/login', function(req, res, next) {
  let {username, password} = req.body
  if (!username || !password) {
    res.json({
      status: 1,
      msg: 'param is empty'
    })
  } else {
    UserModel.findOne({username, password}, (err, doc) => {
      if (err) {
        res.json({
          status: 1,
          msg: 'username or password is wrong',
          msgDB: err.message
        })
      } else if (doc) {
        const userId = doc.userId
        const payload = {username, password, userId}
        const token = jwt.encode(payload, secretKey)
        res.json({
          status: 0,
          msg: 'ok',
          result: {
            username,
            token
          }
        })
      } else {
        res.json({
          status: 1,
          msg: 'username or password is wrong'
        })
      }
    })
  }
});

// 注册
router.post('/register', function(req, res, next) {
  let {username, password} = req.body
  if (!username || !password || password.length < 6) {
    res.json({
      status: 1,
      msg: 'param err'
    })
  }
  UserModel.findOne({username}, (err, doc) => {
    if (err) {
      res.json({
        status: 1,
        msg: 'db err, no why'
      })
    } else if (doc) {
      res.json({
        status: 1,
        msg: 'username is exist'
      })
    } else {
      UserModel.count({}, (err, count) => {
        if (err) {
          res.json({
            status: 1,
            msg: err.message
          })
        } else {
          UserModel.create({username, password, userId: count + 1}, err => {
            if (err) {
              res.json({
                status: 1,
                msg: err.message
              })
            } else {
              res.json({
                status: 0,
                msg: 'register success'
              })
            }
          })
        }
      })
    }
  })
})

// 获取文章
router.get('/articles', function(req, res, next) {
  let { username, articleId, articleType, page } = req.query
  let query = {}
  query = articleId ? {articleId} : {}
  username ? query.username = username : null
  articleType ? query.articleType = articleType : null
  page = page || 1
  const itemsPerPage = 10
  ArticleModel.find(query)
    .limit(itemsPerPage)
    .skip((page - 1) * itemsPerPage)
    .exec((err, doc) => {
      if (err) {
        res.json({
          status: 1,
          msg: err.message
        })
      } else {
        res.json({
          status: 0,
          msg: 'ok',
          result: {
            count: doc.length,
            list: doc
          }
        })
      }
    })
  if (query.articleId) {
    console.log(query.articleId)
    ArticleModel.update(query, {$inc:{"viewed": 1}}, (err, raw) => {
      console.log(err, 'view article log fail')
      console.log(raw)
    })
  } else {
    console.log(query)
  }
  /* ArticleModel.find(query, (err, doc) => {
    if (err) {
      res.json({
        status: 1,
        msg: err.message
      })
    } else {
      res.json({
        status: 0,
        msg: 'ok',
        result: {
          count: doc.length,
          list: doc.limit(itemsPerPage).skip((page - 1) * itemsPerPage)
        }
      })
    }
  }) */

})

// 发表文章
router.post('/new-article', function(req, res, next) {
  const { token } = req.headers
  const { userId } = jwt.decode(token, secretKey, true)
  const { content, author, title, articleType } = req.body
  const id = author + Date.now()
  const docu = {
    username: author,
    content,
    time: Date.now(),
    title,
    articleId: id,
    articleType,
    userId,
    viewed: 0
  }
  ArticleModel.create(docu, err => {
    if (err) {
      res.json({
        status: 1,
        msg: err.message
      })
    } else {
      res.json({
        status: 0,
        msg: 'create article success'
      })
    }
  })
})

// 编辑->更新文章
router.post('/edit-article', function(req, res, next) {
  const { token } = req.headers
  const { username } = jwt.decode(token, secretKey, true)
  const { content, author, title, id, articleType } = req.body
  if (!content || author !== username || !title || !id) {
    res.json({
      status: 1,
      msg: 'params error',
      author,
      username
    })
  } else {
    const doc = {
      content,
      time: Date.now(),
      title
    }
    articleType ? doc.articleType = articleType : null
    ArticleModel.updateOne({username, articleId: id}, doc, (err, raw) => {
      if (err) {
        res.json({
          status: 1,
          msg: err.message
        })
      } else if (raw.n === 0) {
        res.json({
          status: 1,
          msg: '没找到该文章， 或， 不可改别人的文章'
        })
      } else {
        res.json({
          status: 0,
          msg: 'update success'
        })
      }
    })
  }
})

// 删除文章
router.get('/del-article', function(req, res, next) {
  const { id } = req.query
  const { token } = req.headers
  if (!token) {
    res.json({
      status: 1,
      msg: 'param wrong'
    })
  }
  const { username, userId } = jwt.decode(token, secretKey, true)
  if (!id) {
    res.json({
      status: 1,
      msg: 'param wrong'
    })
  }
  const query = {"articleId": id, username, userId}
  ArticleModel.remove(query, (err, raw) => {
      if (err){
        res.json({
          status: 1,
          msg: err.message
        })
      } else if (raw.n === 1 && raw.ok === 1) {
        res.json({
          status: 0,
          msg: 'delete success'
        })
      } else {
        res.json({
          status: 1,
          msg: 'article is not found'
        })
      }
    })
})

// 添加评论
router.post('/new-review', function(req, res, next) {
  const {userId, username} = req._userInfo
  const { articleId, content, mentioned } = req.body
  if (typeof content === 'string' && content.trim()) {
    const time = Date.now()
    const mentionedArr = mentioned instanceof Array ? mentioned : []
    const updateDoc = {
      $push: {
        "reviews":{
          reviewId: articleId + time.toString(36),
          username,
          userId,
          time,
          content,
          mentioned: mentionedArr // @的用户名数组
        }
      }
    }
    ArticleModel.updateOne({articleId}, updateDoc, (err, raw) => {
      if (err) {
        res.json({
          status: 1,
          msg: err.message
        })
      } else if (raw) {
        res.json({
          status: 0,
          raw
        })
      } else {
        res.json({
          status: 1,
          msg: 'article is not found'
        })
      }
    })
  } else {
    res.json({
      status: 1,
      msg: 'param error'
    })
  }

})
// 保存图片
// express.use(bodyParser.json({ limit: '50mb' }))
// express.use(bodyParser.urlencoded({ limit: '50mb', extended: true }))

// router.post('/save-image', (req, res, next)=>{
//   let imgData = req.body.img64
//   if (imgData) {
//     var base64Data = imgData.replace(/^data:image\/\w+;base64,/, '')
//     var dataBuffer = new Buffer(base64Data, 'base64')
//     fs.writeFile('./public/images/image.png', dataBuffer, function(err) {
//       if (err) return
//       console.log('图片保存成功')
//     })
//     console.log(imgData)
//     UserModel.update()
//     res.end('ok')
//   } else {
//     res.json({
//       status: 1,
//       msg: '请传入图片'
//     })
//   }

// })

// 获取所有用户名和id
router.get('/users', (req, res, next) => {
  UserModel.find({}, ("username userId"),(err, doc) => {
    if (err) {
      res.json({
        status: 1,
        msg: err.message
      })
    } else {
      res.json({
        status: 0,
        msg: 'ok',
        result: {
          count: doc.length,
          list: doc
        }
      })
    }
  })
})

module.exports = router;